#include "login.h"
#include "ui_login.h"
#include <QJsonObject>
#include <QJsonParseError>
#include <QMessageBox>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QPainter>
#include "common/logininfoinstance.h"
#include "mainwindow.h"

Login::Login(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Login), p_main(new MainWindow)
{
    ui->setupUi(this);

    //去掉边框
    this->setWindowFlags(windowFlags() | Qt::FramelessWindowHint);
    this->setFont(QFont("宋体", 16, QFont::Bold, false));
    this->setStyleSheet("color: rgb(255, 255, 255");

    connect(ui->title_wg, &TitleWg::closeWindow, [=]()
    {
        if(ui->stackedWidget->currentWidget() == ui->set_page)
        {
            ui->stackedWidget->setCurrentWidget(ui->login_page);
        }
        else if(ui->stackedWidget->currentWidget() == ui->reg_page)
        {
            ui->stackedWidget->setCurrentWidget(ui->login_page);
        }
        else
        {
            this->close();
        }
    });

    connect(ui->title_wg, &TitleWg::showSetwg, [=]()
    {
        ui->address->setText(m_cm.getCfgValue("web_server", "ip"));
        ui->port->setText(m_cm.getCfgValue("web_server", "port"));

        ui->stackedWidget->setCurrentWidget(ui->set_page);
    });

    connect(ui->btn_register, &QToolButton::clicked, [=]()
    {
        ui->stackedWidget->setCurrentWidget(ui->reg_page);
    });

    QString user = m_cm.getCfgValue("login", "user");
    ui->user_login->setText(QByteArray::fromBase64(user.toUtf8()));
    QString remember = m_cm.getCfgValue("login", "remember");
    if("yes" == remember)
    {
        QString password = m_cm.getCfgValue("login", "pwd");
        ui->pwd_login->setText(QByteArray::fromBase64(password.toUtf8()));
        ui->remember_pwd->setChecked(true);
    }

    ui->stackedWidget->setCurrentIndex(0);
    m_cm.getFileTypeList();

//    Common m_cm;

//    cout << "file md5: " << m_cm.getFileMd5(QString("E:\\Software\\Godot_v3.5-stable_win64.zip")) << endl;
}

Login::~Login()
{
    delete ui;
}

void Login::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter p(this);
    QPixmap pixmap(":/images/5160549.jpg");
    p.drawPixmap(0, 0, this->width(), this->width(), pixmap);
}

QByteArray Login::getRegJson(QString user, QString nick, QString pwd, QString phone, QString email)
{
    QJsonObject obj;
    obj.insert("userName", user);
    obj.insert("nickName", nick);
    obj.insert("firstPwd", pwd);
    obj.insert("phone", phone);
    obj.insert("email", email);

    QJsonDocument doc(obj);
    if(doc.isNull() || doc.isEmpty())
    {
        cout << "doc.isNULL || doc.isEmpty";
        return 0;
    }
    return doc.toJson();
}

QByteArray Login::getLoginJson(QString name, QString password)
{
    QJsonObject obj;
    obj.insert("user", name);
    obj.insert("pwd", password);
    QJsonDocument doc(obj);
    return doc.toJson();
}

QStringList Login::parseLoginJson(QByteArray json)
{
    QStringList list;
    QJsonDocument doc = QJsonDocument::fromJson(json);
    if(doc.isObject())
    {
        QJsonObject obj = doc.object();
        list.append(obj.value("code").toString());
        list.append(obj.value("token").toString());
    }

    return list;
}

//服务器设置
void Login::on_server_set_btn_clicked()
{
    QString ip = ui->address->text();
    QString port = ui->port->text();

    QRegExp exp(IP_REG);
    if(!exp.exactMatch(ip))
    {
        QMessageBox::warning(this, "警告", "IP格式不对");
        ui->address->clear();
        ui->address->setFocus();
        return;
    }

    exp.setPattern(PORT_REG);
    if(!exp.exactMatch(port))
    {
        QMessageBox::warning(this, "警告", "Port格式不对");
        ui->port->clear();
        ui->port->setFocus();
        return;
    }

    m_cm.writeWebInfo(ip, port);
    QMessageBox::information(this, "恭喜", "写入成功！");
}

void Login::on_register_btn_clicked()
{
    QString ip = m_cm.getCfgValue("web_server", "ip");
    QString port = m_cm.getCfgValue("web_server", "port");
    QString name = ui->name_reg->text();
    QString nick = ui->nick_name->text();
    QString pwd = ui->pwd_reg->text();
    QString confirm_pwd = ui->pwd_confirm_reg->text();
    QString phone = ui->phone->text();
    QString email = ui->email->text();

    //效验
    QRegExp exp(PASSWD_REG);
    if(!exp.exactMatch(pwd))
    {
        QMessageBox::warning(this, "警告", "Password格式不对");
        ui->pwd_reg->clear();
        ui->pwd_confirm_reg->clear();
        ui->pwd_reg->setFocus();
        return;
    }
    if(pwd.compare(confirm_pwd, Qt::CaseSensitive) != 0)
    {
        QMessageBox::warning(this, "警告", "确认密码不匹配！");
        ui->pwd_confirm_reg->clear();
        ui->pwd_reg->setFocus();
        return;
    }

    exp.setPattern(PHONE_REG);
    if(!exp.exactMatch(phone))
    {
        QMessageBox::warning(this, "警告", "Phone格式不对");
        ui->phone->clear();
        ui->phone->setFocus();
        return;
    }

    exp.setPattern(EMAIL_REG);
    if(!exp.exactMatch(email))
    {
        QMessageBox::warning(this, "警告", "Email格式不对");
        ui->email->clear();
        ui->email->setFocus();
        return;
    }

    //加密
    QString password = m_cm.getStrMd5(pwd);

    QByteArray postData = getRegJson(name, nick, password, phone, email);
    QNetworkAccessManager* manager = m_cm.getNetManager();

    QNetworkRequest request;
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader, postData.size());

    QString url = QString("http://%1:%2/reg").arg(ip).arg(port);
    request.setUrl(QUrl(url));
    QNetworkReply* reply = manager->post(request, postData);

    //接收server返回数据
    connect(reply, &QNetworkReply::readyRead, [=]()
    {
        //返回的数据
        QByteArray jsonData = reply->readAll();
        reply->deleteLater(); //释放

        QString status = m_cm.getCode(jsonData);

        if("002" == status)
        {
            QMessageBox::information(this, "恭喜", "注册成功！");
            ui->user_login->setText(name);
            ui->pwd_login->setText(pwd);

            ui->stackedWidget->setCurrentWidget(ui->login_page);
        }
        else if("003" == status)
        {
            //该用户已存在
            QMessageBox::warning(this, "警告", "该用户已存在");
            return;
        }
        else if("004" == status)
        {
            QMessageBox::critical(this, "报错", "注册失败!");
            return;
        }
    });
}

void Login::on_login_btn_clicked()
{
    QString user = ui->user_login->text();
    QString pwd = ui->pwd_login->text();
    QString ip = m_cm.getCfgValue("web_server", "ip");
    QString port = m_cm.getCfgValue("web_server", "port");

    bool remember = ui->remember_pwd->isChecked();

    //效验
    QRegExp exp(PASSWD_REG);
    if(!exp.exactMatch(pwd))
    {
        QMessageBox::warning(this, "警告", "Password格式不对");
        ui->pwd_reg->clear();
        ui->pwd_confirm_reg->clear();
        ui->pwd_reg->setFocus();
        return;
    }

    //保存数据到配置文件
    m_cm.writeLoginInfo(user, pwd, remember);

    QByteArray data = getLoginJson(user, m_cm.getStrMd5(pwd));

    QNetworkAccessManager* manager = m_cm.getNetManager();
    QNetworkRequest request;

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader, data.size());
    QString url = QString("http://%1:%2/login").arg(ip).arg(port);
    request.setUrl(QUrl(url));
    QNetworkReply* reply = manager->post(request, data);

    cout << data << endl;

    connect(reply, &QNetworkReply::readyRead, [=]()
    {
       QByteArray json = reply->readAll();

       cout << json << endl;

       QStringList list = parseLoginJson(json);
       if(list.at(0) == "000")
       {
           LoginInfoInstance* info = LoginInfoInstance::getInstance();
           info->setLoginInfo(user, ip, port, list.at(1));
           this->hide();
           p_main->showMainWindow();
       }
       else
       {
           QMessageBox::warning(this, "警告", "用户名或密码不正确！");
       }
    });
}
